package com.xsm.activitygroup;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
import com.umeng.analytics.MobclickAgent;
import com.xsm.DataBase.SaveMessage;
import com.xsm.activitygroup.R;
import com.xsm.activitygroup.TypeC.Myhandler;
import com.xsm.activitygroup.activity2.GetNewData;
import com.xsm.adapter.BooksAdapter;
import com.xsm.internet.PostMessage;
import com.xsm.object.BookObject;
public class Tuijian extends Activity{
	PullToRefreshListView listView;
	TextView textView;
	BooksAdapter  adapter;
	Myhandler hanMyhandler;
	ArrayList<BookObject> books=new ArrayList<BookObject>();
	Context context;
int page=0;
String press;
String bookname;
static int Getstate=0;
int state=0;
private boolean scrollFlag = false;// 标记是否滑动
private int lastVisibleItemPosition;// 标记上次滑动位置
private RelativeLayout LoadLayout,ErrorLayout;

protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.tuijian);
	context=this;
	press=getIntent().getExtras().getString("press");
	bookname=getIntent().getExtras().getString("bookname");
	listView=(PullToRefreshListView)findViewById(R.id.tuijianlist);
	textView=(TextView)findViewById(R.id.title);
	LoadLayout=(RelativeLayout)findViewById(R.id.loadlayout);
	ErrorLayout=(RelativeLayout)findViewById(R.id.errorlayout);
	
	
textView.setText("推荐");
adapter=new BooksAdapter(context, books);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		  Intent intent=new Intent();
		  intent.putExtra("ms",books.get(arg2-1));
		  intent.putExtra("index",arg2-1);
		  intent.putExtra("type","tuijian");
		  intent.setClass(context, BookMessage.class);
		 startActivityForResult(intent,2);					
	}
});
	 listView.setOnScrollListener(new OnScrollListener() {
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
				scrollFlag = true;
				} else {
				scrollFlag = false;
				}
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (scrollFlag) {
				if (firstVisibleItem > lastVisibleItemPosition) {
					state=1;
					//上滑
				}
				if (firstVisibleItem < lastVisibleItemPosition) {
					state=0;
					//下滑
				}
				if (firstVisibleItem == lastVisibleItemPosition) {
				return;
				}
				lastVisibleItemPosition = firstVisibleItem;
				}
		}
	});
	 
	 listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
	 if(Getstate==0)
	 {		 
	new getTuijian().execute();
	 }	 
	}});
	 
	 listView.setVisibility(View.GONE);
	 LoadLayout.setVisibility(View.VISIBLE);
	 new getTuijian().execute();
}








public void Back(View view){
	finish();
}

protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}

public void Update(View view){
	LoadLayout.setVisibility(View.VISIBLE);
	ErrorLayout.setVisibility(View.GONE);
	new getTuijian().execute();
}



class getTuijian extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {
		Getstate=1;
		if(state==0)
		page=0;
		else{
		page+=books.size();
		}
		List param=new ArrayList();
		param.add(new BasicNameValuePair("ASK","GetTuijian"));
		param.add(new BasicNameValuePair("press",press));
		param.add(new BasicNameValuePair("page",page+""));
		PostMessage postMessage=new PostMessage(param);
		String result=postMessage.getResult();
		JSONArray array = null;
		try {
	 array=new JSONArray(result);
	JSONObject jobject=new JSONObject();
	if(array.length()>0){
	if(state==0)
	books.clear();
	}
			for(int i=0;i<array.length();i++){
				jobject=array.optJSONObject(i);
				String bookname=jobject.getString("bookname");
				String releaseType=jobject.getString("buytype");
				String time=jobject.getString("time");
				String price=jobject.getString("price");
				String bookType=jobject.getString("booktype");
				String oner=jobject.getString("username");
				String phone=jobject.getString("phone");
				String message=jobject.getString("explain");
				String school=jobject.getString("school");
				String press=jobject.getString("press");
				String goodsid=jobject.getString("goodsid");
				String author=jobject.getString("author");
				String uid=jobject.getString("userid");
				String gparentid=jobject.getString("gparentid");
				String realprice=jobject.getString("realprice");
				String path=jobject.getString("path");
				BookObject object=new BookObject();
				object.setBookName(bookname);
				object.setReleaseType(releaseType);
				object.setTime(time.substring(0,10));
				object.setPrice(price);
				object.setBookType(bookType);
				object.setOner(oner);
				object.setPhone(phone);
				object.setMessage(message);
				object.setPlace(school);
				object.setPress(press);
				object.setGoodsid(goodsid);
				object.setUserid(uid);
				object.setGparentid(gparentid);
				object.setAuthor(author);
				object.setRealprice(realprice);
				object.setPath(path);
				books.add(object);	
			}
		} catch (Exception e) {
			Log.d("my", e+"");
		}
		return result;
	}
	protected void onPostExecute(String result) {
		LoadLayout.setVisibility(View.GONE);
		if(result.equals("-1")){
			ErrorLayout.setVisibility(View.VISIBLE);
		}else {
			listView.setVisibility(View.VISIBLE);
			if(books.size()<5)
			listView.setMode(Mode.PULL_DOWN_TO_REFRESH);
			else {
			listView.setMode(Mode.BOTH);
			}
			adapter.notifyDataSetChanged();	
			if(listView.isRefreshing())
			Getstate=0;
		}
		listView.onRefreshComplete();
		super.onPostExecute(result);
	}
}
}
